package com.lwy.jwt;

import com.lwy.entity.MyBookUser;
import io.jsonwebtoken.*;
import org.springframework.security.core.Authentication;

import java.util.Date;

public class JWTUtils {

    private static  final String ISSUER="lwy";
    private static  final String SING="world";
    private static  final Integer TIME=6000;
    static final  String HEAD = "token";

    //获取token
    public static String getToken(Authentication authentication){
        String name = authentication.getName();
        JwtBuilder jwtBuilder = Jwts.builder()
                //用户名
                .setSubject(name)
                //签发者
                .setIssuer(ISSUER)
                //加密方式，密钥 盐
                .signWith(SignatureAlgorithm.HS512, SING)
                .setExpiration(new Date(System.currentTimeMillis()+1000*TIME))
                .setIssuedAt(new Date());
        MyBookUser principal = (MyBookUser) authentication.getPrincipal();
        jwtBuilder.claim("username",principal.getUsername());
        jwtBuilder.claim("roles",principal.getAuthorities());
        return jwtBuilder.compact();
    }

    public static Claims parse(String token){
        Claims claims = null;
        try {
            Jws<Claims> world = Jwts.parser().setSigningKey("world").parseClaimsJws(token);
            claims = world.getBody();
        }catch (ExpiredJwtException e){
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
        return claims;
    }

    public static String getUsername(String token){
        Claims claims = parse(token);
        String username=null;
        try {
            username = claims.get("username").toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return username;
    }

    public static boolean isExpiration(String token){
        Claims claims = parse(token);
        try {
            return claims.getExpiration().before(new Date());
        }catch (Exception e){
            e.printStackTrace();
        }
        return true;
    }
}

